package com.glela.goods.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.glela.activ.model.OActivContentExpress;
import com.glela.activ.model.OActivContentMoney;
import com.glela.activ.model.OActivGiftProduct;
import com.glela.activ.model.OActivitiesInfo;
import com.glela.activ.service.OActivService;
import com.glela.activ.service.domain.OActivAvlInfoVo;
import com.glela.activ.service.domain.OActivAvlVo;
import com.glela.activ.service.domain.OActivProductParam;
import com.glela.common.constant.CommonConstants;
import com.glela.common.model.ProductTag;
import com.glela.common.util.DateUtil;
import com.glela.common.util.NumberUtil;
import com.glela.goods.dao.ShoppingCartDao;
import com.glela.goods.mapper.GoodsMapper;
import com.glela.goods.mapper.GoodsNavigateMapper;
import com.glela.goods.mapper.InventoryMapper;
import com.glela.goods.mapper.LimitTimeSaleDetailMapper;
import com.glela.goods.mapper.ProductMapper;
import com.glela.goods.mapper.ShoppingCartMapper;
import com.glela.goods.model.Goods;
import com.glela.goods.model.GoodsNavigate;
import com.glela.goods.model.Inventory;
import com.glela.goods.model.LimitTimeSaleDetail;
import com.glela.goods.model.Product;
import com.glela.goods.model.ShoppingCart;
import com.glela.goods.model.SpecificationDetailVo;

import com.glela.goods.model.request.ShoppingCartRequest;
import com.glela.goods.model.vo.OActivVO;
import com.glela.goods.model.vo.ShoppingCartVo;
import com.glela.goods.service.GoodsService;
import com.glela.goods.service.InventoryService;
import com.glela.goods.service.ShoppingCartService;
import com.glela.platform.mapper.OperationLogMapper;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.model.OperationLog;
import com.glela.platform.model.User;
import com.glela.platform.model.request.RequestPageBaseModel;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.UserService;

/**
 *@author liujie
 *@2016年10月20日
 */
@Service("shoppingCartService")
public class ShoppingCartServiceImpl implements ShoppingCartService{

	@Autowired
	private ShoppingCartDao shoppingCartDao;

	@Autowired
	private ShoppingCartMapper shoppingCartMapper;
	
	@Autowired
	private OperationLogMapper operationLogMapper;

	@Autowired
	private InventoryMapper inventoryMapper;

	@Autowired
	private LimitTimeSaleDetailMapper limitTimeSaleDetailMapper;

	@Autowired
	private GoodsService goodsService;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private BaseRestrictionsService baseRestrictionsService;


	@Autowired
	private ProductMapper productMapper;


	@Autowired
	private GoodsMapper goodsMapper;

	@Autowired
	private GoodsNavigateMapper goodsNavigateMapper;

	@Autowired
	private InventoryService inventoryService;

	@Autowired
	private OActivService oActivService;

	
	@Autowired
	private UserService userService;
	
	@Override
	public int insert(ShoppingCart record) {
		// TODO Auto-generated method stub
		return shoppingCartDao.insert(record);
	}
	@Override
	public int insertSelective(ShoppingCart record) {
		// TODO Auto-generated method stub
		return shoppingCartDao.insertSelective(record);
	}
	@Override
	public int deleteByPrimaryKey(Integer id) {
		// TODO Auto-generated method stub
		return shoppingCartDao.deleteByPrimaryKey(id);
	}
	@Override
	public int updateByPrimaryKeySelective(ShoppingCart record) {
		// TODO Auto-generated method stub
		return shoppingCartDao.updateByPrimaryKeySelective(record);
	}
	@Override
	public List<ShoppingCartVo> selectMoreInfoByUserIdPage(
			RequestPageBaseModel requestPageBaseModel) {
		// TODO Auto-generated method stub
		return shoppingCartDao.selectMoreInfoByUserIdPage(requestPageBaseModel);
	}
	@Override
	public ShoppingCart selectByUserInventoryId(Long userId, Long inventoryId) {
		// TODO Auto-generated method stub
		return shoppingCartDao.selectByUserInventoryId(userId, inventoryId);
	}

	public int deleteShopppingCart(Long userId, Integer id) {
		
		OperationLog log = new OperationLog();
		log.setObjId(userId.intValue());
		log.setObjName(String.valueOf(userId));
		log.setModule("shoppingcart");
		log.setOperateType("delete");
		Long createLongTime = ((new Date().getTime()) / 1000);
		log.setCreatedAt(createLongTime.intValue());
		log.setDescription("用户删除购物车 参数 userId" + userId + "    id:" + id );
		operationLogMapper.insert(log);
		
		if (id == null || id == 0 ) {// 删除所有无效购物车
			return shoppingCartMapper.deleteInvalidShopppingCart(userId.intValue());
		} else {
			return shoppingCartMapper.deleteByPrimaryKey(id);
		}
		
		
	}
	@Override
	public String selectImgPathByProductID(long proID) {
		Product p= shoppingCartDao.selectspecificationByProID(proID);
		String StrIMG="";
		//找到货品 再去找图片
		if(p!=null){ 
          List<SpecificationDetailVo>	 list=
        		 JSON.parseArray(p.getSpecDesc(), SpecificationDetailVo.class);
          if(list!=null&&list.size()>0){ 
        	  SpecificationDetailVo sVo=list.get(0);
        	  StrIMG=shoppingCartDao.selectIMGBydetailAndGoodID(sVo.getSpecificationDetailId(),p.getGoodId());
          }
		}
		  return StrIMG;
	}
	
	
	@Override
	public void updateRemoveShoppingCart(ResponseUser user , Long orderoObjectId) {
		if(orderoObjectId  == null ) {
			return;
		}
		if(user == null) {
			return;
		}
		if(user.getRoleId() == 7) {
			return ;
		}
		Map<String,Object> map = new HashedMap<String,Object>();
		map.put("orderObjectId", orderoObjectId);
		map.put("userId", user.getUserId());
		List<Integer> list = shoppingCartMapper.selectDeleteShoppingCartId(map);
		for(Integer shopCartId : list) {
			shoppingCartMapper.deleteByPrimaryKey(shopCartId);
		}
	}

	@Override
	public Map<String, Object> getShoppingCart(ShoppingCartRequest gouCart) {
		Map<String,Object > returnMap = new HashMap<String,Object>();//返回值
		//用来存储商品信息（key 规格ID,value 购物车对象vo）
//		HashMap<String, ShoppingCartVo> shoppingCartVoHashMap = new HashMap<>();
//		//用于存储活动对应的商品信息（key 活动ID ，value 购物车对象vo）
//		HashMap<String, ShoppingCartVo> activityCartVoHashMap = new HashMap<>();
		//存储所有活动ID集合
//		List<String> idsList = new ArrayList<String>();

		//存储当前购物车中已选中的商品列表
		List<ShoppingCartVo> selectedProductList = new ArrayList<ShoppingCartVo>();
		//需求后期修改，购物车不分页，限制最多添加99个SKU
		gouCart.setPageNumber(1);
		gouCart.setPageSize(CommonConstants.SHOPPING_CART_PAGE_SIZE);
		// 实时判断当前用户推荐人，用来防止之前加入购物车的时候，推荐人和当前推荐人不一致的时候，对价格产生的影响
		User recommentUser = userService.selectRecommendFromByUserId(gouCart.getUserId());
		int public_user_id = baseRestrictionsService.getBaseRestrictionsForCache("xz_jj").getExperience();
		if(recommentUser == null) {
			recommentUser = userMapper.selectByPrimaryKey(Long.valueOf(public_user_id));
		}
		ShoppingCart cart = new ShoppingCart();
		cart.setUserId(gouCart.getUserId());
		//cart.setProductId(gouCart.getProductId());
		// 分页处理
		PageHelper.startPage(gouCart.getPageNumber(), gouCart.getPageSize());
//		Page<ShoppingCart> page = (Page<ShoppingCart>) shoppingCartMapper.selectAll(cart);
		//用购物车表左关联活动表查询
		Page<ShoppingCartVo> page = (Page<ShoppingCartVo>) shoppingCartMapper.selectAllProduct(cart);

		//****************************
		returnMap.put("pageNumber", gouCart.getPageNumber());
		returnMap.put("pageSize", gouCart.getPageSize());
		returnMap.put("isHasNextPage", page.toPageInfo().isHasNextPage());
//		returnMap.put("productCount", page.getTotal());
		returnMap.put("productCount", page.size());
		returnMap.put("storeName", "小铺来了");
		//***************************
		ShoppingCartVo vo;
		List<ShoppingCartVo> returnList = new ArrayList<ShoppingCartVo>();
		List<ShoppingCartVo> availableList = new ArrayList<ShoppingCartVo>();
//		long start = System.currentTimeMillis();
		for (int i = 0; page != null && i < page.size(); i++) {
			ShoppingCartVo c = page.get(i);
//
			vo = new ShoppingCartVo();
			//查询商品对应的活动标签和广告语集合activitiesList
			//新建Map（一个map就是一个活动内容）
			if (!c.getActivId().equals("0")) {
				List<Map<String, Object>> activitiesList = new ArrayList<Map<String,Object>>();
				OActivitiesInfo oActivitiesInfo = this.oActivService.getOActivitiesInfo(c.getGoodId(),Long.parseLong(c.getActivId()));
				if (oActivitiesInfo != null) {
					if (!CollectionUtils.isEmpty(oActivitiesInfo.getoActivContentExpressList())){
						Map<String, Object> oagfMap = new HashMap<String, Object>();
						String tag = "";
						List<Map<String, Object>> oaList = new ArrayList<Map<String,Object>>();
						String sloganList = "";
						for (OActivContentExpress oace : oActivitiesInfo.getoActivContentExpressList()) {
							Map<String, Object> oaMap = new HashMap<String, Object>();
							oaMap.put("slogan", oace.getActivTitle());
//						oaMap.put("number", 1);
//						oaMap.put("jumpParameter", oActivitiesInfo.getoActiv().getId());
							oaList.add(oaMap);
							if ("".equals(tag)) {
								tag = oace.getTagName();
							}
							sloganList = sloganList +oace.getActivTitle() + ",";
						}
						oagfMap.put("tag",tag);
						oagfMap.put("eventType",1);
						oagfMap.put("list",oaList);
						oagfMap.put("sloganList", sloganList.substring(0,sloganList.length()-1));
						activitiesList.add(oagfMap);
					}
					if (!CollectionUtils.isEmpty(oActivitiesInfo.getoActivContentMoneyList())){
						Map<String, Object> oagfMap = new HashMap<String, Object>();
						String tag = "";
						List<Map<String, Object>> oaList = new ArrayList<Map<String,Object>>();
						String sloganList = "";
						for (OActivContentMoney oacm : oActivitiesInfo.getoActivContentMoneyList()) {
							Map<String, Object> oaMap = new HashMap<String, Object>();
							oaMap.put("slogan", oacm.getActivTitle());
//						oaMap.put("number", 1);
//						oaMap.put("jumpParameter", 1);
							oaList.add(oaMap);
							if ("".equals(tag)) {
								tag = oacm.getTagName();
							}
							sloganList = sloganList +oacm.getActivTitle() + ",";
						}
						oagfMap.put("tag",tag);
						oagfMap.put("eventType",0);
						oagfMap.put("list",oaList);
						oagfMap.put("sloganList", sloganList.substring(0,sloganList.length()-1));
						activitiesList.add(oagfMap);
					}
					if (!CollectionUtils.isEmpty(oActivitiesInfo.getoActivGiftProductList())){
						Map<String, Object> oagfMap = new HashMap<String, Object>();
						String tag = "";
						List<Map<String, Object>> oaList = new ArrayList<Map<String,Object>>();
						String sloganList = "";
						for (OActivGiftProduct oagf : oActivitiesInfo.getoActivGiftProductList()) {
							Map<String, Object> oaMap = new HashMap<String, Object>();
							oaMap.put("slogan", oagf.getActivTitle());
//						oaMap.put("number", oagf.getGiftNum());
//						oaMap.put("jumpParameter", oagf.getGoodsId());
							oaList.add(oaMap);
							if ("".equals(tag)) {
								tag = oagf.getTagName();
							}
							sloganList = sloganList +oagf.getActivTitle() + ",";
						}
						oagfMap.put("tag",tag);
						oagfMap.put("eventType",2);
						oagfMap.put("list",oaList);
						oagfMap.put("sloganList", sloganList.substring(0,sloganList.length()-1));
						activitiesList.add(oagfMap);
					}
					OActivVO vo1 = new OActivVO();
					vo1.setOActivVO(oActivitiesInfo.getoActiv());
					vo.setoActivVO(vo1);
				}
//				Map<String, Object> activities = new HashMap<String, Object>();
//				activities.put("activitiesList", activitiesList);
//				c.getoActivVO().getActivitiesList().addAll(activitiesList);
				if (null != c.getoActivVO()) {
					vo.getoActivVO().getActivitiesList().addAll(activitiesList);
				}
			}else{//没有活动直接放查询出来的活动对象
				vo.setoActivVO(c.getoActivVO());
			}
			vo.setSelected(c.getSelected());
			/********************************
			 * 添加公共显示信息： 名称，图片，规格 数量
			 *************************************************************/
			vo.setActivId(c.getActivId());
			vo.setId(c.getId());
			vo.setInventoryId(c.getInventoryId());
			vo.setGoodsName("");
			vo.setProductNum(c.getProductNum());
			vo.setSpecName("");
			vo.setProductTags(goodsService.getGoodsTag(c.getGoodId(), c.getProductId()));
			vo.setGoodId(c.getGoodId());
			vo.setProductId(c.getProductId());
			vo.setUserId(c.getUserId());
			vo.setAvailable(c.getAvailable());
			vo.setAvailableMsg(c.getAvailableMsg());
			Product product = productMapper.selectProductByIdNoStatus(c.getProductId());
			if(product == null) {
				vo.setAvailable(0);
				vo.setAvailableMsg("商品已下架");
				c.setAvailable(0);
				c.setAvailableMsg("商品已下架");
				shoppingCartMapper.updateByPrimaryKey(c);
				availableList.add(vo);
				continue ;
			}
			Goods goods = goodsMapper.selectGoodsByIdForAll(product.getGoodId());

			if(goods == null) {
				vo.setAvailable(0);
				vo.setAvailableMsg("商品已下架");
				c.setAvailable(0);
				c.setAvailableMsg("商品已下架");
				shoppingCartMapper.updateByPrimaryKey(c);
				availableList.add(vo);
				continue ;

			}
			if(!StringUtils.isBlank(product.getSpecInfo())  && product.getSpecInfo().indexOf("|") > 0) {
				String spec_id = null;
				//取规格图片
				if(product.getSpecInfo().split("\\|") != null && product.getSpecInfo().split("\\|").length > 0) {
					spec_id = product.getSpecInfo().split("\\|")[0];
				}
				String specImage = null;
				if(!StringUtils.isBlank(spec_id)) {
					specImage = goodsMapper.getSpecificationImagesPath(goods.getId(),Integer.valueOf(spec_id));
				}
				if(!StringUtils.isBlank(specImage)) {
					vo.setImagePath(specImage);
				}else {
					List<GoodsNavigate>   navigateList =     goodsNavigateMapper.selectGoodsNavigateByGoodId(goods.getId());
					/*if(navigateList != null && navigateList.size() < 0) {
						vo.setImagePath(navigateList.get(0).getNavigateImage());
					}*/
					if(navigateList != null && !CollectionUtils.isEmpty(navigateList)) {
						vo.setImagePath(navigateList.get(0).getNavigateImage());
					}
				}
			}else {
				List<GoodsNavigate>   navigateList =     goodsNavigateMapper.selectGoodsNavigateByGoodId(goods.getId());
				/*if(navigateList != null && navigateList.size() < 0) {
					vo.setImagePath(navigateList.get(0).getNavigateImage());
				}*/
				if(navigateList != null && !CollectionUtils.isEmpty(navigateList)) {
					vo.setImagePath(navigateList.get(0).getNavigateImage());
				}
			}
			vo.setGoodsName(goods.getName());
			vo.setSpecName(product.getSpecName());
			vo.setGoodsType(goods.getGoodsType());
			vo.setBrandId(goods.getBrandId());
			vo.setGoodsName(goods.getName());
			if(product.getStatus() == 0) { //若需要对GOODS有效性进行判断，在这里添加
				vo.setAvailable(0);
				vo.setAvailableMsg("商品已下架");
				c.setAvailable(0);
				c.setAvailableMsg("商品已下架");
				shoppingCartMapper.updateByPrimaryKey(c);
				availableList.add(vo);
				continue ;
			}

			//失效商品产进行再次计算
			if(c.getAvailable() == 0) {
				availableList.add(vo);
				c.setAvailable(0);
				c.setAvailableMsg(c.getAvailableMsg());
				shoppingCartMapper.updateByPrimaryKey(c);
				continue ;
			}
			if(goods.getGoodsType() == 0) {
				vo.setAvailable(0);
				vo.setAvailableMsg("商品已下架");
				c.setAvailable(0);
				c.setAvailableMsg("商品已下架");
				shoppingCartMapper.updateByPrimaryKey(c);
				availableList.add(vo);
				continue ;

			}
			/********************************
			 * 添加公共显示信息： 名称，图片，规格 结束
			 ********************************************************/

			/*************************
			 * 取当前产品的库存 通过库存记录取出产品价格（非抢购商品）
			 *********************************/
			Inventory inventory = inventoryMapper.selectAllInventoryByProductId(c.getProductId());
			/*************************
			 * 取当前产品的库存 通过库存记录取出产品价格（非抢购商品） 结束
			 *********************************/
			long cart_sale_price = c.getSalePrice();
			/**************************根据下架状态设置产品失效**************************************/
			//跟小朱确认，规格产品表中的这个状态用来标识 ，是否下架
			Goods haveGoods = goodsMapper.selectGoodsById(product.getGoodId());
			if(haveGoods == null || product.getStatus() == 0) {
				c.setAvailable(0);
				c.setAvailableMsg("商品已下架");
				shoppingCartMapper.updateByPrimaryKey(c);
				vo.setSalePrice(0l);
				vo.setShowPrice("0");
				vo.setAvailable(0);
				//vo.setAvailableMsg("价格当前价格上涨了: " + sortPrice + " 元, 失效！");
				vo.setAvailableMsg("商品已下架");
				availableList.add(vo);
				continue ;
			};

			/**************************根据下架状态设置产品失效  结束**********************************/
			// 先判断该规格商品（当前时间）是否存在分时抢购活动中，如果存在则忽略身份，直接显示抢购价
			// 判断是不是分时抢购（进行中的商品）
			Map<String, Object> map = new HashMap<String, Object>();

			map.put("sku_no", c.getProductId());
			map.put("current_time", new Date());
			LimitTimeSaleDetail limitTimeSaleDetail = limitTimeSaleDetailMapper.selectByProductId(map);
			if (limitTimeSaleDetail != null) {// 该商品当前在分时抢购中
				// 抢购中的商品取抢购价，如果当前抢购价格跟购物车中存的价格相比有了降价需加上降价标记，如果价格上涨，则加上失效标识，失效原因：商品价格上涨，更新购物车这两个字段。
				long sortPrice = limitTimeSaleDetail.getProductSalePrice() - cart_sale_price;
				/******************************根据产品库存计算购物车商品是否失效************************************************/
				int inventoryNumber = (limitTimeSaleDetail.getSkuCount() > inventory.getInventoryNum()) ? inventory.getInventoryNum() : limitTimeSaleDetail.getSkuCount();
				if(inventoryNumber < 1) {
					c.setAvailable(0);
					c.setAvailableMsg("商品已经卖光了");
					shoppingCartMapper.updateByPrimaryKey(c);
					vo.setSalePrice(0l);
					vo.setShowPrice("0");
					vo.setAvailable(0);
					//vo.setAvailableMsg("价格当前价格上涨了: " + sortPrice + " 元, 失效！");
					vo.setAvailableMsg("商品已经卖光了");
					availableList.add(vo);
					continue ;
				}

				/******************************根据产品库存计算购物车商品是否失效  结束*************************************************/

				if (sortPrice > 0) {// 涨价了,购物车该条记录失效
					c.setAvailable(0);
					c.setAvailableMsg("商品已不能购买");
					shoppingCartMapper.updateByPrimaryKey(c);
					// 产品经理确认，失效产品不显示价格
					vo.setSalePrice(0l);
					vo.setShowPrice("0");
					vo.setAvailable(0);
					vo.setAvailableMsg("商品已不能购买");
					availableList.add(vo);
					continue ;
				} else {
					// 计算降价标签
					if (sortPrice != 0) {
						vo.setDescPrice("已降 ￥ " + String.valueOf(NumberUtil.getMoney(Math.abs(sortPrice))));
					}
					vo.setSalePrice(limitTimeSaleDetail.getProductSalePrice());
					vo.setShowPrice(String.valueOf(NumberUtil.getMoney(limitTimeSaleDetail.getProductSalePrice())));
					//c.setSalePrice(limitTimeSaleDetail.getProductSalePrice());//系统判断出来当前产品降价后只在前端体现，暂不更新购物车中的价格
					//shoppingCartMapper.updateByPrimaryKey(c); // 将最新价格更新到购物车中
					// 添加： 特惠标签
				}
				//这里会覆盖掉原有的降价提示，因为这个提示比降价提示重要，会影响到下单
				if(inventoryNumber < c.getProductNum()) {
					vo.setDescPrice("库存小于购买数量  ");
				}

			} else {// 不是分时抢购商品

				/******************************根据产品库存计算购物车商品是否失效************************************************/
				if(inventory.getInventoryNum() < 1) {
					c.setAvailable(0);
					c.setAvailableMsg("商品已经卖光了");
					shoppingCartMapper.updateByPrimaryKey(c);
					vo.setSalePrice(0);
					vo.setShowPrice("0");
					vo.setAvailable(0);
					vo.setAvailableMsg("商品已经卖光了");
					availableList.add(vo);
					continue ;
				}
				/******************************根据产品库存计算购物车商品是否失效 结束************************************************/
				if (recommentUser.getId() == public_user_id) {// 当前用户，为校妆姐姐下面的会员
					Long sortPrice = inventory.getXzSalePrice() - cart_sale_price;
					if (sortPrice > 0) {// 涨价了,购物车该条记录失效
						c.setAvailable(0);
						c.setAvailableMsg("商品已不能购买");
						shoppingCartMapper.updateByPrimaryKey(c);
						// 产品经理确认，失效产品不显示价格
						vo.setSalePrice(0);
						vo.setShowPrice("0");
						vo.setAvailable(0);
						vo.setAvailableMsg("商品已不能购买");
					} else {// 降价了
						// 计算降价标签
						if (sortPrice != 0) {
							//NumberUtil.getFloatPrice(inventory.getXzSalePrice())
							Long _sortPrice = Math.abs(sortPrice);
							vo.setDescPrice("已降 ￥ " + String.valueOf(NumberUtil.getMoney(_sortPrice.intValue())));
						}
						vo.setSalePrice(inventory.getXzSalePrice());
						vo.setShowPrice(String.valueOf(NumberUtil.getMoney(inventory.getXzSalePrice())));
						//c.setSalePrice(inventory.getXzSalePrice()); ////系统判断出来当前产品降价后只在前端体现，暂不更新购物车中的价格
						//shoppingCartMapper.updateByPrimaryKey(c); // 将最新价格更新到购物车中
					}
				} else {// 当前用户，为一般店主下面的用户
					Long sortPrice = inventory.getSalePrice() - cart_sale_price;
					if (sortPrice > 0) {// 涨价了,购物车该条记录失效
						c.setAvailable(0);
						c.setAvailableMsg("商品已不能购买");
						shoppingCartMapper.updateByPrimaryKey(c);
						// 产品经理确认，失效产品不显示价格
						vo.setSalePrice(0);
						vo.setShowPrice("0");
						vo.setAvailable(0);
						vo.setAvailableMsg("商品已不能购买");
					} else {// 降价了
						// 计算降价标签
						if (sortPrice != 0) {
							vo.setDescPrice("已降 ￥ " + String.valueOf(NumberUtil.getMoney(Math.abs(sortPrice))) );
						}
						vo.setSalePrice(inventory.getSalePrice());
						vo.setShowPrice(String.valueOf(NumberUtil.getMoney(inventory.getSalePrice())));
						//c.setSalePrice(inventory.getSalePrice());
						//shoppingCartMapper.updateByPrimaryKey(c); // 将最新价格更新到购物车中
					}
				}

				//这里会覆盖掉原有的降价提示，因为这个提示比降价提示重要，会影响到下单
				if(inventory.getInventoryNum() < c.getProductNum()) {
					vo.setDescPrice("库存小于购买数量  ");
				}

				// 判断是不是分时抢购 （预热中的商品），预热中的商品显示(根据店主，校妆姐姐身份显示价格)，加上预热标记，
				// 如果非预热中的，也是根据（一般店主，校妆姐姐）取价格，如果取到的当前价格跟购物车中存的价格相比有了降价
				// 需加上降价标记，如果价格上涨，则加上失效标识，失效原因：商品价格上涨，更新购物车这两个字段。
				if(vo.getAvailable() != 0 ) {//当产品失效的时候，不进行预热判断
					Map<String, Object> warmupParamMap = new HashMap<String, Object>();
					// 先判断该规格商品（当前时间）是否存在分时抢购活动中，如果存在则忽略身份，直接显示抢购价
					Date nextDay = DateUtil.parse(DateUtil.getNextDate() + " 00:00:00");
					warmupParamMap.put("sku_no", c.getProductId());
					warmupParamMap.put("currentEndTime", nextDay);
					warmupParamMap.put("currentTime", new Date());
					String warmupBegin = limitTimeSaleDetailMapper.selectWarmupByProduct(warmupParamMap);
					if (!StringUtils.isBlank(warmupBegin)) {// 该商品为：预热中商品，按角色
						Date begin_date = DateUtil.parse(warmupBegin);
						Calendar calendar = Calendar.getInstance();
						calendar.setTime(begin_date);
						int month = calendar.get(Calendar.MONTH) + 1;
						int day = calendar.get(Calendar.DAY_OF_MONTH);
						int hour = calendar.get(Calendar.HOUR_OF_DAY);
						vo.setWarmupTitle(month + "月" + day + "日  " + hour + " 开始");
						vo.setWarmupTag(new ProductTag("#ff4b7a","预热"));
					}
				}
			}
			if(vo.getAvailable() == 0) {
				availableList.add(vo);
			}else {
				returnList.add(vo);
			}
			//封装到Map
//			shoppingCartVoHashMap.put(c.getProductId().toString(),vo);
//			activityCartVoHashMap.put(c.getActivId(),vo);
			if (1==vo.getSelected()) {//已勾选的商品
				selectedProductList.add(vo);
			}
		}
		returnList.addAll(availableList);

		//将处于同一活动的商品放在一起（无效）
//		List<ShoppingCartVo> returnList1= new ArrayList<ShoppingCartVo>();
//		returnList1.addAll(returnList);
//		Collections.sort(returnList, new Comparator<ShoppingCartVo>() {
//			@Override
//			public int compare(ShoppingCartVo o1, ShoppingCartVo o2) {
////				if(i == 0){
////					return Integer.parseInt(o1.getActivId())  - Integer.parseInt(o2.getActivId());
////				}
//				int i = o2.getId() - o2.getId();//倒序
//				if (o2.getActivId() == o1.getActivId()) {
//					return i;
//				} else {
//					return Integer.parseInt(o1.getActivId())  - Integer.parseInt(o2.getActivId());
//				}
////				return i;
//			}
//		});
//		returnMap.put("productListOld", returnList);//原来返回结果（已弃用）

		//用于存储活动对应的商品集合(同一个活动只有第一个商品显示活动内容)(key:活动ID)
		HashMap<String, List<ShoppingCartVo>>  shoppingmap  = new LinkedHashMap<>() ;
		HashMap<String, List<ShoppingCartVo>>  invalidMap  = new LinkedHashMap<>() ;
		List<ShoppingCartVo> pList ;
		for (ShoppingCartVo sCv : returnList) {//无活动商品放在后边
			if (!sCv.getActivId().equals("0")) {
				if (sCv.getAvailable() == 0) {//失效放入活动ID为0也就是不参与活动
//					pList = new ArrayList<ShoppingCartVo>();
//					pList.add(sCv);
//					invalidMap.put("0", pList);
//					continue;
					//失效商品不显示活动标签和广告语
					OActivVO oActivVO = new OActivVO();
					oActivVO.setId(Long.parseLong(sCv.getActivId()));
					sCv.setoActivVO(oActivVO);
					if (null == invalidMap.get("0")) {
						pList = new ArrayList<ShoppingCartVo>();
						pList.add(sCv);
						invalidMap.put("0", pList);
					} else {
						invalidMap.get("0").add(sCv);
					}
					continue;
				}
				if (null != shoppingmap.get(sCv.getActivId())) {
					OActivVO oActivVO = new OActivVO();
					oActivVO.setId(Long.parseLong(sCv.getActivId()));
					sCv.setoActivVO(oActivVO);
					shoppingmap.get(sCv.getActivId()).add(sCv);
				}else{
					pList = new ArrayList<ShoppingCartVo>();
					pList.add(sCv);
					shoppingmap.put(sCv.getActivId(), pList);
				}
			}else{//没有活动
				if (null == invalidMap.get(sCv.getActivId())) {
					pList = new ArrayList<ShoppingCartVo>();
					pList.add(sCv);
					invalidMap.put(sCv.getActivId(), pList);
				} else {
					invalidMap.get(sCv.getActivId()).add(sCv);
				}
			}
		}
		List<ShoppingCartVo> returnListNew = new ArrayList<ShoppingCartVo>();//存放最终返回的结果
		for (String s : shoppingmap.keySet()) {
			List<ShoppingCartVo> shoppingCartVos = shoppingmap.get(s);
			returnListNew.addAll(shoppingCartVos);
		}
		//无活动商品和失效商品
		for (String s : invalidMap.keySet()) {
			List<ShoppingCartVo> shoppingCarts = invalidMap.get(s);
			returnListNew.addAll(shoppingCarts);
		}
		returnMap.put("productList", returnListNew);
//		System.out.println(System.currentTimeMillis() - start+"...........................");

		//开始计算商品的折扣（满减）等优惠信息
		//**********初始化********************
		int selectedCount = 0;//总勾选商品数量
		BigDecimal totalAmount = BigDecimal.ZERO;//总金额
		BigDecimal discountAmount = BigDecimal.ZERO;//折扣金额
		BigDecimal payAmount = BigDecimal.ZERO;//支付金额
		if (null != selectedProductList && !CollectionUtils.isEmpty(selectedProductList)) {
			Set<OActivProductParam> set = new HashSet<OActivProductParam>();
			for (ShoppingCartVo sVo : selectedProductList) {//获取活动折扣
				selectedCount += sVo.getProductNum();
				totalAmount = totalAmount.add(
						new BigDecimal(sVo.getSalePrice()).multiply(new BigDecimal(sVo.getProductNum()))
								.divide(new BigDecimal(100),2, RoundingMode.HALF_UP));
				OActivProductParam oActivProductParam = new OActivProductParam();
				oActivProductParam.setProductId(sVo.getProductId());
				oActivProductParam.setQuantity(sVo.getProductNum());
				oActivProductParam.setSalePrice(sVo.getSalePrice());
//				oActivProductParam.setPromotionFee(0L);
				set.add(oActivProductParam);
			}
			//计算折扣(暂时先try起来处理异常)
			OActivAvlInfoVo oActivAvlInfoVo = null;
			try {
				oActivAvlInfoVo = oActivService.queryProductActiv(set);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (null != oActivAvlInfoVo) {
				//活动商品集合
				Collection<OActivAvlVo> avlActivsList = oActivAvlInfoVo.getAvlActivs();
				if (null != avlActivsList && !CollectionUtils.isEmpty(avlActivsList)) {
					//活动商品总优惠
					for (OActivAvlVo oActivAvlVo : avlActivsList) {
						discountAmount = discountAmount.add(new BigDecimal(oActivAvlVo.getDiscontFee()));
					}
				}
				//非活动商品集合
				Collection<OActivProductParam> uavlActivProductsList = oActivAvlInfoVo.getUavlActivProducts();
				if (null != uavlActivProductsList && !CollectionUtils.isEmpty(uavlActivProductsList)) {
					for (OActivProductParam oActivProductParam : uavlActivProductsList) {
						discountAmount = discountAmount.add (new BigDecimal(oActivProductParam.getPromotionFee()));
					}
				}
			}
			//计算实际支付金额
			discountAmount = discountAmount.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
			payAmount = totalAmount.subtract(discountAmount);

		}
		returnMap.put("selectedCount",selectedCount);
		returnMap.put("totalAmount",totalAmount.toString());
		returnMap.put("discountAmount",discountAmount.toString());
		returnMap.put("payAmount",payAmount.toString());
//		System.out.println(System.currentTimeMillis() - start+"最后！！！！！！");
		return returnMap;
	}


	@Override
	public Map<String,Object> updateSelected(ShoppingCartRequest gouCart){
		Map<String,Object> dataMap = new HashedMap<String ,Object>();
		if(gouCart.getAllSelect() == CommonConstants.SHOPPING_CART_PRODUCT_SINGER_SELECTED) {
			ShoppingCart _shoppingCart = new ShoppingCart();
			_shoppingCart.setUserId(gouCart.getUserId());
			_shoppingCart.setProductId(gouCart.getProductId());
			_shoppingCart.setInventoryId(gouCart.getInventoryId());
			_shoppingCart.setAvailable(1);
			List<ShoppingCart> _userCartProductList =  shoppingCartMapper.selectAll(_shoppingCart);
			if(_userCartProductList != null && _userCartProductList.size() > 0) {
				ShoppingCart selectedRow = _userCartProductList.get(0);
				selectedRow.setSelected(gouCart.getSelected());
				selectedRow.setUpdateTime(DateUtil.getNow());
				shoppingCartMapper.updateByPrimaryKeySelective(selectedRow);
			}
			dataMap.put("selected", gouCart.getSelected());
		}else if(gouCart.getAllSelect() == CommonConstants.SHOPPING_CART_PRODUCT_ALL_SELECTED) {
			ShoppingCart _shoppingCart = new ShoppingCart();
			_shoppingCart.setUserId(gouCart.getUserId());
			_shoppingCart.setAvailable(1);
			List<ShoppingCart> _userCartProductList =  shoppingCartMapper.selectAll(_shoppingCart);
			for(ShoppingCart cart : _userCartProductList) {
				cart.setSelected(gouCart.getSelected());
				cart.setUpdateTime(DateUtil.getNow());
				shoppingCartMapper.updateByPrimaryKeySelective(cart);
			}
		}
		return dataMap;
	}

	@Override
	public List<ShoppingCart> getShoppingCartProducts(ShoppingCartRequest gouCart) {
		return shoppingCartMapper.selectAll(gouCart);
	}

	//简化版查询购物车（不匹配活动信息）
    @Override
    public Map<String, Object> getShoppingCartSimplify(ShoppingCartRequest gouCart) {
        Map<String, Object> returnMap = new HashMap<String, Object>();//返回值
        List<ShoppingCartVo> selectedProductList = new ArrayList<ShoppingCartVo>();
        //需求后期修改，购物车不分页，限制最多添加99个SKU
        gouCart.setPageNumber(1);
        gouCart.setPageSize(CommonConstants.SHOPPING_CART_PAGE_SIZE);
        // 实时判断当前用户推荐人，用来防止之前加入购物车的时候，推荐人和当前推荐人不一致的时候，对价格产生的影响
        User recommentUser = userService.selectRecommendFromByUserId(gouCart.getUserId());
        int public_user_id = baseRestrictionsService.getBaseRestrictionsForCache("xz_jj").getExperience();
        if (recommentUser == null) {
            recommentUser = userMapper.selectByPrimaryKey(Long.valueOf(public_user_id));
        }
        ShoppingCart cart = new ShoppingCart();
        cart.setUserId(gouCart.getUserId());
        //cart.setProductId(gouCart.getProductId());
        // 分页处理
        PageHelper.startPage(gouCart.getPageNumber(), gouCart.getPageSize());
        //用购物车表左关联活动表查询
        Page<ShoppingCartVo> page = (Page<ShoppingCartVo>) shoppingCartMapper.selectAllProductSimplify(cart);

        //****************************
        returnMap.put("pageNumber", gouCart.getPageNumber());
        returnMap.put("pageSize", gouCart.getPageSize());
        returnMap.put("isHasNextPage", page.toPageInfo().isHasNextPage());
//		returnMap.put("productCount", page.getTotal());
        returnMap.put("productCount", page.size());
        returnMap.put("storeName", "小铺来了");
        //***************************
        ShoppingCartVo vo;
        List<ShoppingCartVo> returnList = new ArrayList<ShoppingCartVo>();
        List<ShoppingCartVo> availableList = new ArrayList<ShoppingCartVo>();
//		long start = System.currentTimeMillis();
        for (int i = 0; page != null && i < page.size(); i++) {
            ShoppingCartVo c = page.get(i);
            vo = new ShoppingCartVo();
            OActivVO oAc = new OActivVO();
            oAc.setId(0L);
            vo.setoActivVO(oAc);
            vo.setSelected(c.getSelected());
            /********************************
             * 添加公共显示信息： 名称，图片，规格 数量
             *************************************************************/
            vo.setActivId("0");//全部改成未参加活动
            vo.setId(c.getId());
            vo.setInventoryId(c.getInventoryId());
            vo.setGoodsName("");
            vo.setProductNum(c.getProductNum());
            vo.setSpecName("");
            vo.setProductTags(goodsService.getGoodsTag(c.getGoodId(), c.getProductId()));
            vo.setGoodId(c.getGoodId());
            vo.setProductId(c.getProductId());
            vo.setUserId(c.getUserId());
            vo.setAvailable(c.getAvailable());
            vo.setAvailableMsg(c.getAvailableMsg());
            Product product = productMapper.selectProductByIdNoStatus(c.getProductId());
            if (product == null) {
                vo.setAvailable(0);
                vo.setAvailableMsg("商品已下架");
                c.setAvailable(0);
                c.setAvailableMsg("商品已下架");
                shoppingCartMapper.updateByPrimaryKey(c);
                availableList.add(vo);
                continue;
            }
            Goods goods = goodsMapper.selectGoodsByIdForAll(product.getGoodId());

            if (goods == null) {
                vo.setAvailable(0);
                vo.setAvailableMsg("商品已下架");
                c.setAvailable(0);
                c.setAvailableMsg("商品已下架");
                shoppingCartMapper.updateByPrimaryKey(c);
                availableList.add(vo);
                continue;

            }
            if (!StringUtils.isBlank(product.getSpecInfo()) && product.getSpecInfo().indexOf("|") > 0) {
                String spec_id = null;
                //取规格图片
                if (product.getSpecInfo().split("\\|") != null && product.getSpecInfo().split("\\|").length > 0) {
                    spec_id = product.getSpecInfo().split("\\|")[0];
                }
                String specImage = null;
                if (!StringUtils.isBlank(spec_id)) {
                    specImage = goodsMapper.getSpecificationImagesPath(goods.getId(), Integer.valueOf(spec_id));
                }
                if (!StringUtils.isBlank(specImage)) {
                    vo.setImagePath(specImage);
                } else {
                    List<GoodsNavigate> navigateList = goodsNavigateMapper.selectGoodsNavigateByGoodId(goods.getId());
                    if (navigateList != null && navigateList.size() < 0) {
                        vo.setImagePath(navigateList.get(0).getNavigateImage());
                    }
                }
            } else {
                List<GoodsNavigate> navigateList = goodsNavigateMapper.selectGoodsNavigateByGoodId(goods.getId());
                if (navigateList != null && navigateList.size() < 0) {
                    vo.setImagePath(navigateList.get(0).getNavigateImage());
                }
            }
            vo.setGoodsName(goods.getName());
            vo.setSpecName(product.getSpecName());
            vo.setGoodsType(goods.getGoodsType());
            vo.setBrandId(goods.getBrandId());
            vo.setGoodsName(goods.getName());
            if (product.getStatus() == 0) { //若需要对GOODS有效性进行判断，在这里添加
                vo.setAvailable(0);
                vo.setAvailableMsg("商品已下架");
                c.setAvailable(0);
                c.setAvailableMsg("商品已下架");
                shoppingCartMapper.updateByPrimaryKey(c);
                availableList.add(vo);
                continue;
            }

            //失效商品产进行再次计算
            if (c.getAvailable() == 0) {
                availableList.add(vo);
                c.setAvailable(0);
                c.setAvailableMsg(c.getAvailableMsg());
                shoppingCartMapper.updateByPrimaryKey(c);
                continue;
            }
            if (goods.getGoodsType() == 0) {
                vo.setAvailable(0);
                vo.setAvailableMsg("商品已下架");
                c.setAvailable(0);
                c.setAvailableMsg("商品已下架");
                shoppingCartMapper.updateByPrimaryKey(c);
                availableList.add(vo);
                continue;

            }
            /********************************
             * 添加公共显示信息： 名称，图片，规格 结束
             ********************************************************/

            /*************************
             * 取当前产品的库存 通过库存记录取出产品价格（非抢购商品）
             *********************************/
            Inventory inventory = inventoryMapper.selectAllInventoryByProductId(c.getProductId());
            /*************************
             * 取当前产品的库存 通过库存记录取出产品价格（非抢购商品） 结束
             *********************************/
            long cart_sale_price = c.getSalePrice();
            /**************************根据下架状态设置产品失效**************************************/
            //跟小朱确认，规格产品表中的这个状态用来标识 ，是否下架
            Goods haveGoods = goodsMapper.selectGoodsById(product.getGoodId());
            if (haveGoods == null || product.getStatus() == 0) {
                c.setAvailable(0);
                c.setAvailableMsg("商品已下架");
                shoppingCartMapper.updateByPrimaryKey(c);
                vo.setSalePrice(0l);
                vo.setShowPrice("0");
                vo.setAvailable(0);
                //vo.setAvailableMsg("价格当前价格上涨了: " + sortPrice + " 元, 失效！");
                vo.setAvailableMsg("商品已下架");
                availableList.add(vo);
                continue;
            }
            ;

            /**************************根据下架状态设置产品失效  结束**********************************/
            // 先判断该规格商品（当前时间）是否存在分时抢购活动中，如果存在则忽略身份，直接显示抢购价
            // 判断是不是分时抢购（进行中的商品）
            Map<String, Object> map = new HashMap<String, Object>();

            map.put("sku_no", c.getProductId());
            map.put("current_time", new Date());
            LimitTimeSaleDetail limitTimeSaleDetail = limitTimeSaleDetailMapper.selectByProductId(map);
            if (limitTimeSaleDetail != null) {// 该商品当前在分时抢购中
                // 抢购中的商品取抢购价，如果当前抢购价格跟购物车中存的价格相比有了降价需加上降价标记，如果价格上涨，则加上失效标识，失效原因：商品价格上涨，更新购物车这两个字段。
                long sortPrice = limitTimeSaleDetail.getProductSalePrice() - cart_sale_price;
                /******************************根据产品库存计算购物车商品是否失效************************************************/
                int inventoryNumber = (limitTimeSaleDetail.getSkuCount() > inventory.getInventoryNum()) ? inventory.getInventoryNum() : limitTimeSaleDetail.getSkuCount();
                if (inventoryNumber < 1) {
                    c.setAvailable(0);
                    c.setAvailableMsg("商品已经卖光了");
                    shoppingCartMapper.updateByPrimaryKey(c);
                    vo.setSalePrice(0l);
                    vo.setShowPrice("0");
                    vo.setAvailable(0);
                    //vo.setAvailableMsg("价格当前价格上涨了: " + sortPrice + " 元, 失效！");
                    vo.setAvailableMsg("商品已经卖光了");
                    availableList.add(vo);
                    continue;
                }

                /******************************根据产品库存计算购物车商品是否失效  结束*************************************************/

                if (sortPrice > 0) {// 涨价了,购物车该条记录失效
                    c.setAvailable(0);
                    c.setAvailableMsg("商品已不能购买");
                    shoppingCartMapper.updateByPrimaryKey(c);
                    // 产品经理确认，失效产品不显示价格
                    vo.setSalePrice(0l);
                    vo.setShowPrice("0");
                    vo.setAvailable(0);
                    vo.setAvailableMsg("商品已不能购买");
                    availableList.add(vo);
                    continue;
                } else {
                    // 计算降价标签
                    if (sortPrice != 0) {
                        vo.setDescPrice("已降 ￥ " + String.valueOf(NumberUtil.getMoney(Math.abs(sortPrice))));
                    }
                    vo.setSalePrice(limitTimeSaleDetail.getProductSalePrice());
                    vo.setShowPrice(String.valueOf(NumberUtil.getMoney(limitTimeSaleDetail.getProductSalePrice())));
                    //c.setSalePrice(limitTimeSaleDetail.getProductSalePrice());//系统判断出来当前产品降价后只在前端体现，暂不更新购物车中的价格
                    //shoppingCartMapper.updateByPrimaryKey(c); // 将最新价格更新到购物车中
                    // 添加： 特惠标签
                }
                //这里会覆盖掉原有的降价提示，因为这个提示比降价提示重要，会影响到下单
                if (inventoryNumber < c.getProductNum()) {
                    vo.setDescPrice("库存小于购买数量  ");
                }

            } else {// 不是分时抢购商品

                /******************************根据产品库存计算购物车商品是否失效************************************************/
                if (inventory.getInventoryNum() < 1) {
                    c.setAvailable(0);
                    c.setAvailableMsg("商品已经卖光了");
                    shoppingCartMapper.updateByPrimaryKey(c);
                    vo.setSalePrice(0);
                    vo.setShowPrice("0");
                    vo.setAvailable(0);
                    vo.setAvailableMsg("商品已经卖光了");
                    availableList.add(vo);
                    continue;
                }
                /******************************根据产品库存计算购物车商品是否失效 结束************************************************/
                if (recommentUser.getId() == public_user_id) {// 当前用户，为校妆姐姐下面的会员
                    Long sortPrice = inventory.getXzSalePrice() - cart_sale_price;
                    if (sortPrice > 0) {// 涨价了,购物车该条记录失效
                        c.setAvailable(0);
                        c.setAvailableMsg("商品已不能购买");
                        shoppingCartMapper.updateByPrimaryKey(c);
                        // 产品经理确认，失效产品不显示价格
                        vo.setSalePrice(0);
                        vo.setShowPrice("0");
                        vo.setAvailable(0);
                        vo.setAvailableMsg("商品已不能购买");
                    } else {// 降价了
                        // 计算降价标签
                        if (sortPrice != 0) {
                            //NumberUtil.getFloatPrice(inventory.getXzSalePrice())
                            Long _sortPrice = Math.abs(sortPrice);
                            vo.setDescPrice("已降 ￥ " + String.valueOf(NumberUtil.getMoney(_sortPrice.intValue())));
                        }
                        vo.setSalePrice(inventory.getXzSalePrice());
                        vo.setShowPrice(String.valueOf(NumberUtil.getMoney(inventory.getXzSalePrice())));
                        //c.setSalePrice(inventory.getXzSalePrice()); ////系统判断出来当前产品降价后只在前端体现，暂不更新购物车中的价格
                        //shoppingCartMapper.updateByPrimaryKey(c); // 将最新价格更新到购物车中
                    }
                } else {// 当前用户，为一般店主下面的用户
                    Long sortPrice = inventory.getSalePrice() - cart_sale_price;
                    if (sortPrice > 0) {// 涨价了,购物车该条记录失效
                        c.setAvailable(0);
                        c.setAvailableMsg("商品已不能购买");
                        shoppingCartMapper.updateByPrimaryKey(c);
                        // 产品经理确认，失效产品不显示价格
                        vo.setSalePrice(0);
                        vo.setShowPrice("0");
                        vo.setAvailable(0);
                        vo.setAvailableMsg("商品已不能购买");
                    } else {// 降价了
                        // 计算降价标签
                        if (sortPrice != 0) {
                            vo.setDescPrice("已降 ￥ " + String.valueOf(NumberUtil.getMoney(Math.abs(sortPrice))));
                        }
                        vo.setSalePrice(inventory.getSalePrice());
                        vo.setShowPrice(String.valueOf(NumberUtil.getMoney(inventory.getSalePrice())));
                        //c.setSalePrice(inventory.getSalePrice());
                        //shoppingCartMapper.updateByPrimaryKey(c); // 将最新价格更新到购物车中
                    }
                }

                //这里会覆盖掉原有的降价提示，因为这个提示比降价提示重要，会影响到下单
                if (inventory.getInventoryNum() < c.getProductNum()) {
                    vo.setDescPrice("库存小于购买数量  ");
                }

                // 判断是不是分时抢购 （预热中的商品），预热中的商品显示(根据店主，校妆姐姐身份显示价格)，加上预热标记，
                // 如果非预热中的，也是根据（一般店主，校妆姐姐）取价格，如果取到的当前价格跟购物车中存的价格相比有了降价
                // 需加上降价标记，如果价格上涨，则加上失效标识，失效原因：商品价格上涨，更新购物车这两个字段。
                if (vo.getAvailable() != 0) {//当产品失效的时候，不进行预热判断
                    Map<String, Object> warmupParamMap = new HashMap<String, Object>();
                    // 先判断该规格商品（当前时间）是否存在分时抢购活动中，如果存在则忽略身份，直接显示抢购价
                    Date nextDay = DateUtil.parse(DateUtil.getNextDate() + " 00:00:00");
                    warmupParamMap.put("sku_no", c.getProductId());
                    warmupParamMap.put("currentEndTime", nextDay);
                    warmupParamMap.put("currentTime", new Date());
                    String warmupBegin = limitTimeSaleDetailMapper.selectWarmupByProduct(warmupParamMap);
                    if (!StringUtils.isBlank(warmupBegin)) {// 该商品为：预热中商品，按角色
                        Date begin_date = DateUtil.parse(warmupBegin);
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(begin_date);
                        int month = calendar.get(Calendar.MONTH) + 1;
                        int day = calendar.get(Calendar.DAY_OF_MONTH);
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        vo.setWarmupTitle(month + "月" + day + "日  " + hour + " 开始");
                        vo.setWarmupTag(new ProductTag("#ff4b7a", "预热"));
                    }
                }
            }
            if (vo.getAvailable() == 0) {
                availableList.add(vo);
            } else {
                returnList.add(vo);
            }
            if (1 == vo.getSelected()) {//已勾选的商品
                selectedProductList.add(vo);
            }
        }
        returnList.addAll(availableList);
        returnMap.put("productList", returnList);
        //**********初始化********************
        int selectedCount = 0;//总勾选商品数量
        BigDecimal totalAmount = BigDecimal.ZERO;//总金额
        BigDecimal discountAmount = BigDecimal.ZERO;//折扣金额
        BigDecimal payAmount = BigDecimal.ZERO;//支付金额
        if (null != selectedProductList && !CollectionUtils.isEmpty(selectedProductList)) {
//            Set<OActivProductParam> set = new HashSet<OActivProductParam>();
            for (ShoppingCartVo sVo : selectedProductList) {//获取活动折扣
                selectedCount += sVo.getProductNum();
                totalAmount = totalAmount.add(
                        new BigDecimal(sVo.getSalePrice()).multiply(new BigDecimal(sVo.getProductNum()))
                                .divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
//                OActivProductParam oActivProductParam = new OActivProductParam();
//                oActivProductParam.setProductId(sVo.getProductId());
//                oActivProductParam.setQuantity(sVo.getProductNum());
//                oActivProductParam.setSalePrice(sVo.getSalePrice());
//                set.add(oActivProductParam);
            }
            //计算折扣(暂时先try起来处理异常)
//            OActivAvlInfoVo oActivAvlInfoVo = null;
//            try {
//                oActivAvlInfoVo = oActivService.queryProductActiv(set);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            if (null != oActivAvlInfoVo) {
//                //活动商品集合
//                Collection<OActivAvlVo> avlActivsList = oActivAvlInfoVo.getAvlActivs();
//                if (null != avlActivsList && !CollectionUtils.isEmpty(avlActivsList)) {
//                    //活动商品总优惠
//                    for (OActivAvlVo oActivAvlVo : avlActivsList) {
//                        discountAmount = discountAmount.add(new BigDecimal(oActivAvlVo.getDiscontFee()));
//                    }
//                }
//                //非活动商品集合
//                Collection<OActivProductParam> uavlActivProductsList = oActivAvlInfoVo.getUavlActivProducts();
//                if (null != uavlActivProductsList && !CollectionUtils.isEmpty(uavlActivProductsList)) {
//                    for (OActivProductParam oActivProductParam : uavlActivProductsList) {
//                        discountAmount = discountAmount.add(new BigDecimal(oActivProductParam.getPromotionFee()));
//                    }
//                }
//            }
            //计算实际支付金额
            discountAmount = discountAmount.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
            payAmount = totalAmount.subtract(discountAmount);
        }
        returnMap.put("selectedCount", selectedCount);
        returnMap.put("totalAmount", totalAmount.toString());
        returnMap.put("discountAmount", discountAmount.toString());
        returnMap.put("payAmount", payAmount.toString());
        return returnMap;
    }
}
